package com.lishu.carsafe.activity;

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.github.mikephil.charting.charts.PieChart;
import com.lishu.carsafe.R;
import com.lishu.carsafe.adapter.DayGridViewAdapter;
import com.lishu.carsafe.http.HttpBase;
import com.lishu.carsafe.http.HttpLoader;
import com.lishu.carsafe.model.BaseModel;
import com.lishu.carsafe.model.CarOptionModel;
import com.lishu.carsafe.model.StatisticDetailModel;
import com.lishu.carsafe.model.TaskModel;
import com.lishu.carsafe.model.entity.DataCharge;
import com.lishu.carsafe.model.entity.MileageAndDuration;
import com.lishu.carsafe.model.entity.ScheduleAndTask;
import com.lishu.carsafe.model.entity.StatisticValue;
import com.lishu.carsafe.model.entity.VehicleId;
import com.lishu.carsafe.utils.ListUtil;
import com.lishu.carsafe.utils.TimeUtil;
import com.lishu.carsafe.utils.ToastUtil;
import com.lishu.carsafe.widget.MyDatePickerDialog;
import com.lishu.carsafe.widget.NoScrollGridView;
import com.lishu.carsafe.widget.SpinnerNaturePopWindow;

import java.util.Calendar;
import java.util.List;

public class StatisticsActivity extends StatisticsChartActivity implements View.OnClickListener {
    private SpinnerNaturePopWindow mSpinnerProjectPopWindow;
    private TextView car_name;
    private NoScrollGridView gv_mile_duration, gv_charge, gv_schedule_task;
    private DayGridViewAdapter mMileDurationGvAdapter, mChargeGvAdapter, mScheduleTaskGvAdapter;
    private MileageAndDuration mileageAndDuration;
    private DataCharge dataCharge;
    private ScheduleAndTask scheduleAndTask;
    private List<StatisticValue> mileValueList, durationValueList, powerValueList, chargeValueList, scheduleValueList, taskValueList;
    //选择的状况
    private String selectedCarId = "1";
    private String selectedDateRange = "2020-05";
    private String selectedDisplayType = "0";
    private Calendar calender = Calendar.getInstance();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_statistics);

        initView();
        initEvent();
        initDate();
        getStatisticCarOption();
    }

    @Override
    protected void initView() {
        super.initView();
        setTopTitle("统计分析");

        gv_mile_duration = findViewById(R.id.gv_mile_duration);
        gv_charge = findViewById(R.id.gv_charge);
        gv_schedule_task = findViewById(R.id.gv_schedule_task);
        mMileDurationGvAdapter = new DayGridViewAdapter(this, 1);
        mChargeGvAdapter = new DayGridViewAdapter(this, 2);
        mScheduleTaskGvAdapter = new DayGridViewAdapter(this, 3);
        gv_mile_duration.setAdapter(mMileDurationGvAdapter);
        gv_charge.setAdapter(mChargeGvAdapter);
        gv_schedule_task.setAdapter(mScheduleTaskGvAdapter);

        car_name = findViewById(R.id.car_name);
        //车辆下拉选择列表
        mSpinnerProjectPopWindow = new SpinnerNaturePopWindow(this, new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                VehicleId vehicleId = (VehicleId) parent.getItemAtPosition(position);
                getStatisticDetailByCar(vehicleId);
                mSpinnerProjectPopWindow.dismiss();
            }
        });
    }

    private void initEvent() {
        title_right_layout.setOnClickListener(this);
        select_date.setOnClickListener(this);
        select_car_layout.setOnClickListener(this);

        mile_text.setOnClickListener(this);
        duration_text.setOnClickListener(this);
        daily_power_text.setOnClickListener(this);
        charge_num_text.setOnClickListener(this);
        schedule_text.setOnClickListener(this);
        task_text.setOnClickListener(this);
    }

    private void initDate() {
        selectedDateRange = TimeUtil.getCurDatetimeByPattern("yyyy-MM");
        select_date.setText(TimeUtil.getCurDatetimeByPattern("yyyy年MM月"));
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_right_layout:
                changeDisplayByType(selectedDisplayType);
                break;
            case R.id.select_date:
                showDatePickerDialog(selectedDisplayType);
                break;
            case R.id.select_car_layout:
                mSpinnerProjectPopWindow.setWidth(car_name.getWidth());
                mSpinnerProjectPopWindow.showAsDropDown(car_name);
                break;

            case R.id.mile_text:
                clickMileAndDuration("mile");
                setMileAndDurationTotal("mile", mileageAndDuration.getSumMileage());
                mMileDurationGvAdapter.setData(mileValueList);
                break;
            case R.id.duration_text:
                clickMileAndDuration("duration");
                setMileAndDurationTotal("duration", mileageAndDuration.getSumDuration());
                mMileDurationGvAdapter.setData(durationValueList);
                break;
            case R.id.daily_power_text:
                clickPowerAndCharge("power");
                setPowerAndChargeTotal("power", dataCharge.getSumPowerConsumption());
                mChargeGvAdapter.setData(powerValueList);
                break;
            case R.id.charge_num_text:
                clickPowerAndCharge("charge");
                setPowerAndChargeTotal("charge", dataCharge.getSumCycleCount());
                mChargeGvAdapter.setData(chargeValueList);
                break;
            case R.id.schedule_text:
                clickScheduleAndTask("schedule");
                setScheduleAndTaskTotal("schedule", scheduleAndTask.getSumSchedule());
                mScheduleTaskGvAdapter.setData(scheduleValueList);
                break;
            case R.id.task_text:
                clickScheduleAndTask("task");
                setScheduleAndTaskTotal("task", scheduleAndTask.getSumTask());
                mScheduleTaskGvAdapter.setData(taskValueList);
                break;
            default:
                break;
        }
    }

    private void changeDisplayByType(String disType){
        if("0".equals(disType)){
            selectedDisplayType = "1";
            display_type.setText(R.string.display_by_year);
            layout_mile_duration_month.setVisibility(View.GONE);
            layout_power_charge_month.setVisibility(View.GONE);
            layout_schedule_task_month.setVisibility(View.GONE);
            layout_mile_duration_year.setVisibility(View.VISIBLE);
            layout_power_charge_year.setVisibility(View.VISIBLE);
            layout_schedule_task_year.setVisibility(View.VISIBLE);

            select_date.setText(TimeUtil.formatYearTime(selectedDateRange));
        }else{
            selectedDisplayType = "0";
            display_type.setText(R.string.display_by_month);
            layout_mile_duration_month.setVisibility(View.VISIBLE);
            layout_power_charge_month.setVisibility(View.VISIBLE);
            layout_schedule_task_month.setVisibility(View.VISIBLE);
            layout_mile_duration_year.setVisibility(View.GONE);
            layout_power_charge_year.setVisibility(View.GONE);
            layout_schedule_task_year.setVisibility(View.GONE);

            select_date.setText(TimeUtil.formatMonthTime(selectedDateRange));
        }
        refreshStatisticDateByOptions();
    }

    private void showDatePickerDialog(final String curTab) {
        DatePickerDialog dialog = new MyDatePickerDialog(StatisticsActivity.this, 1,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        monthOfYear = monthOfYear + 1;
                        //修改时间显示，例如 7月8日，显示为 07月08日
                        String myMonth, myDay;
                        if(monthOfYear < 10){
                            myMonth = "0" + monthOfYear;
                        }else{
                            myMonth = "" + monthOfYear;
                        }
                        if(dayOfMonth < 10){
                            myDay = "0" + dayOfMonth;
                        }else{
                            myDay = "" + dayOfMonth;
                        }

                        if ("0".equals(curTab)) {
                            selectedDateRange = year + "-" + myMonth;
                            select_date.setText(year + "年" + myMonth + "月");
                        } else if ("1".equals(curTab)) {
                            selectedDateRange = year + "-01";
                            select_date.setText(year + "年");
                        }
                        refreshStatisticDateByOptions();
                    }
                },
                calender.get(Calendar.YEAR), // 传入年份
                calender.get(Calendar.MONTH), // 传入月份
                calender.get(Calendar.DAY_OF_MONTH) // 传入天数
        );
        dialog.show();

        DatePicker dp = findDatePicker((ViewGroup) dialog.getWindow().getDecorView());

        if (dp != null) {
            if ("0".equals(curTab)) {//只显示年月，隐藏掉日
                ((ViewGroup)((ViewGroup)dp.getChildAt(0)).getChildAt(0))
                        .getChildAt(2).setVisibility(View.GONE);
            } else if ("1".equals(curTab)) {//只显示年，隐藏掉日月
                ((ViewGroup)((ViewGroup)dp.getChildAt(0)).getChildAt(0))
                        .getChildAt(2).setVisibility(View.GONE);
                ((ViewGroup)((ViewGroup)dp.getChildAt(0)).getChildAt(0))
                        .getChildAt(1).setVisibility(View.GONE);
            }
        }
    }

    /**
     * 从当前Dialog中查找DatePicker子控件
     */
    private DatePicker findDatePicker(ViewGroup group) {
        if (group != null) {
            for (int i = 0, j = group.getChildCount(); i < j; i++) {
                View child = group.getChildAt(i);
                if (child instanceof DatePicker) {
                    return (DatePicker) child;
                } else if (child instanceof ViewGroup) {
                    DatePicker result = findDatePicker((ViewGroup) child);
                    if (result != null)
                        return result;
                }
            }
        }
        return null;
    }

    private void refreshStatisticDateByOptions(){
        getStatisticDetail(selectedCarId, selectedDisplayType, selectedDateRange);
    }

    private void getStatisticDetailByCar(VehicleId vehicleId) {
        car_name.setText(vehicleId.getName());
        selectedCarId = vehicleId.getId();
        refreshStatisticDateByOptions();
    }

    //{"code":0,"msg":"success","data":{
    // "alarmInfo":{"sumCount":5,"alarms":[{"name":"车灯故障","count":2},{"name":"遇障停车","count":3}]}}}
    private void getStatisticDetail(String vehicleId, final String type, final String range) {
        show("数据加载中...");
        HttpLoader.getStatisticDetail(vehicleId, type, range, new HttpBase.IResponseListener() {
            @Override
            public void onResponse(BaseModel model) {
                hide();
                if (model == null) {
                    ToastUtil.showShort(R.string.please_check_network);
                    return;
                }
                if (!model.success()) {
                    ToastUtil.showShort(getString(R.string.get_data_fail) + model.getMsg());
                    return;
                }

                StatisticDetailModel.StatisticDetail statisticDetail = ((StatisticDetailModel) model).getData();
                if("0".equals(type)){
                    showDataUIByMonth(statisticDetail, range);
                }else{
                    showDataUIByYear(statisticDetail, range);
                }
            }
        });
    }

    private void showDataUIByYear(StatisticDetailModel.StatisticDetail statisticDetail, String range) {
        mileageAndDuration = statisticDetail.getMileageAndDuration();
        total_mile.setText(mileageAndDuration.getSumMileage() + "km");
        total_duration.setText(mileageAndDuration.getSumDuration() + "h");
        List<String> mileList = mileageAndDuration.getMileages();
        List<String> durationList = mileageAndDuration.getDurations();

        dataCharge = statisticDetail.getDataCharge();
        total_power.setText(dataCharge.getSumPowerConsumption() + "kw·h");
        total_charge.setText(dataCharge.getSumCycleCount() + "次");
        List<String> powerList = dataCharge.getPowerConsumptions();
        List<String> chargeCountList = dataCharge.getCycleCounts();

        scheduleAndTask = statisticDetail.getScheduleAndTask();
        total_schedule.setText(scheduleAndTask.getSumSchedule() + "h");
        total_task.setText(scheduleAndTask.getSumTask() + "次");
        List<String> scheduleList = scheduleAndTask.getSchedules();
        List<String> taskList = scheduleAndTask.getTasks();

        //饼状图
        setPieData(alarm_chart, statisticDetail.getAlarmInfo());
        //柱状图
        setLineBarData(mileList, mMileList);
        setLineBarData(durationList, mDurationList);
        setLineBarData(powerList, mPowerList);
        setLineBarData(chargeCountList, mChargeCountList);
        setLineBarData(scheduleList, mScheduleList);
        setLineBarData(taskList, mTaskList);
        showLineBarData();
    }

    private void showDataUIByMonth(StatisticDetailModel.StatisticDetail statisticDetail, String range) {
        mileageAndDuration = statisticDetail.getMileageAndDuration();
        mileValueList = transformToValueList(range, mileageAndDuration.getMileages());//里程
        durationValueList = transformToValueList(range, mileageAndDuration.getDurations()); //时长
        setMileAndDurationTotal("mile", mileageAndDuration.getSumMileage());
        mMileDurationGvAdapter.setData(mileValueList);

        dataCharge = statisticDetail.getDataCharge();
        powerValueList = transformToValueList(range, dataCharge.getPowerConsumptions());//电耗量
        chargeValueList = transformToValueList(range, dataCharge.getCycleCounts());//充电次数
        setPowerAndChargeTotal("power", dataCharge.getSumPowerConsumption());
        mChargeGvAdapter.setData(powerValueList);

        scheduleAndTask = statisticDetail.getScheduleAndTask();
        scheduleValueList = transformToValueList(range, scheduleAndTask.getSchedules());
        taskValueList = transformToValueList(range, scheduleAndTask.getTasks());
        setScheduleAndTaskTotal("schedule", scheduleAndTask.getSumSchedule());
        mScheduleTaskGvAdapter.setData(scheduleValueList);

        //饼状图
        setPieData(alarm_chart, statisticDetail.getAlarmInfo());
    }

    //{"code":0,"msg":"success","data":[{"name":"vf","id":7},{"name":"1号车","id":1},{"name":"2号车","id":2}]}
    private void getStatisticCarOption() {
        HttpLoader.getStatisticCarOption(new HttpBase.IResponseListener() {
            @Override
            public void onResponse(BaseModel model) {
                if (model == null) {
                    ToastUtil.showShort(R.string.please_check_network);
                    return;
                }
                if (!model.success()) {
                    ToastUtil.showShort(getString(R.string.get_data_fail) + model.getMsg());
                    return;
                }

                List<VehicleId> carOptionList = ((CarOptionModel) model).getData();
                if (!ListUtil.isEmpty(carOptionList)) {
                    mSpinnerProjectPopWindow.setData(carOptionList);
                    getStatisticDetailByCar(carOptionList.get(0));
                }
            }
        });
    }
}
